﻿using Rhino;
using System;
using System.Reflection;
using System.Threading;

namespace AiMoCore
{
    partial class CSharpScriptInstance
    {
        #region Loop

        Thread loopThread;
        /// <summary>
        /// 开启循环
        /// </summary>
        public void LoopOn()
        {
            if (!OnLoop)
            {
                Type typeFromHandle = typeof(CSharpScriptInstance);
                Type type = GetType();
                if (type.GetMethod("Loop", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).DeclaringType != typeFromHandle)
                {
                    OnLoop = true;
                    previewer.LoopOn = true;
                    loopThread = new Thread(StartLoop);
                    loopThread.Start();
                }
            }
        }
        public void LoopOff()
        {
            OnLoop = false;
            Thread.Sleep(300);
            loopThread?.Abort();
        }
        internal bool OnLoop { get; private set; } = true;
        void StartLoop()
        {
            try
            {
                while (OnLoop && previewer.Enabled)
                {
                    Loop();
                }
            }
            catch (Exception ex)
            {
                RhinoApp.WriteLine("Loop() exit with exception:\n" + ex.ToString());
            }
        }
        public virtual void Loop()
        {

        }

        /// <summary>
        /// 暂停一段时间
        /// </summary>
        public void Sleep(int milliseconds)
        {
            Thread.Sleep(milliseconds);
        }

        #endregion
    }
}
